package com.jy.appmarket.activity;

import com.jy.app.market.idata.data.Login;
import com.jy.appmarket.AppMarketApplication;
import com.jy.appmarket.R;
import com.jy.appmarket.dialog.WaitDialog;
import com.jy.appmarket.network.engine.BaseNetEngine;
import com.jy.appmarket.network.engine.ModifyUserInfoNetEngine;
import com.jy.appmarket.network.engine.UserIconNetEngine;
import com.jy.appmarket.network.resultdata.ModifyUserInfoResult;
import com.jy.appmarket.network.resultdata.UserIconResult;
import com.jy.appmarket.network.task.NetTask;
import com.jy.appmarket.network.task.NetTask.NetTaskListener;
import com.jy.appmarket.utils.LoginUtil;
import com.jy.appmarket.view.CircleImageView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.analytics.MobclickAgent;

import android.app.ActionBar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class ModifyUserInfoActivity extends Activity implements
		OnClickListener, OnDateSetListener, OnCheckedChangeListener,NetTaskListener {
	public static final String EXTRA_NAME = "name";
	public static final String EXTRA_IS_SHOW_MENU = "is_show_menu";
	private static final int REQUEST_GALLERY = 0;
	
	private NetTask mNetTask;
	private NetTask mNetTask2;
	private CircleImageView mHeadImage;
	private EditText mNickNameEdit;
	private RadioGroup mSexRadioGroup;
	private RadioButton mSexBoyRadio;
	private RadioButton mSexGirlRadio;
	private EditText mBirthdayEdit;
	private TextView mSelectHeadTv;
	
	private DatePickerDialog mDatePickerDialog;
	private WaitDialog mWaitDialog;
	
	private boolean mIsShowMenu;
	private String mName;
	private String mNickName;
	private String mSex;
	private String mBirthday;
	private Login mLogin;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_modify_user_info);
		
		getExtras();
		initTitle();
		initViews();
	}

	private void getExtras() {
		if (getIntent() != null) {
			Bundle extras = getIntent().getExtras();
			if (extras != null) {
				mName = extras.getString(EXTRA_NAME);
				mIsShowMenu = extras.getBoolean(EXTRA_IS_SHOW_MENU, false);
			}
		}
	}
	
	private void initTitle() {
		ActionBar actionBar = getActionBar();
		actionBar.setDisplayUseLogoEnabled(false);
		actionBar.setDisplayShowHomeEnabled(false);
		actionBar.setDisplayHomeAsUpEnabled(true);
		
		if (AppMarketApplication.isLogin()) {
			Login login = AppMarketApplication.getLogin();
			if (!TextUtils.isEmpty(login.getIconUrl()) || !TextUtils.isEmpty(login.getNickName())) {
				mName = mName.replace("完善", "修改");
			}
		}
		actionBar.setTitle(mName);
	}
	
	private void initViews() {
		mHeadImage = findViewById(R.id.head_icon);
		mNickNameEdit = findViewById(R.id.nick_name_edit);
		mSexRadioGroup = findViewById(R.id.sex_radio_group);
		mSexBoyRadio = findViewById(R.id.boy_radio_btn);
		mSexGirlRadio = findViewById(R.id.gril_radio_btn);
		mBirthdayEdit = findViewById(R.id.birthday_edit);
		mSelectHeadTv = findViewById(R.id.select_head_text);
		
		findViewById(R.id.head_layout).setOnClickListener(this);
		findViewById(R.id.finish_btn).setOnClickListener(this);
		
		mSexRadioGroup.setOnCheckedChangeListener(this);
		//AIP17(4.2)以下，paddingLeft不计ButtonDrawable的宽度，xml中设置paddingLeft容易造成按钮与文字重合
		if (Build.VERSION.SDK_INT < 17) {
			BitmapFactory.Options opts = new BitmapFactory.Options();
			opts.inJustDecodeBounds = true;
			BitmapFactory.decodeResource(this.getResources(),
					R.drawable.icon_boy_n, opts);
			int paddingLeft = opts.outWidth
					+ mSexBoyRadio.getCompoundPaddingLeft();
			mSexBoyRadio.setPadding(paddingLeft, 0, 0, 0);
			mSexGirlRadio.setPadding(paddingLeft, 0, 0, 0);
		}
				
		mBirthdayEdit.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					showDatePickerDialog();
					break;
				case MotionEvent.ACTION_UP:
					v.performClick();
					break;
				default:
					break;
				}
				return false;
			}
		});
		
		if (AppMarketApplication.isLogin()) {
			Login login = AppMarketApplication.getLogin();
			if (!TextUtils.isEmpty(login.getIconUrl())) {
				mSelectHeadTv.setText("修改头像");
				ImageLoader.getInstance().displayImage(login.getIconUrl(), mHeadImage, new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisk(true)
						.resetViewBeforeLoading(false).build());
			} else {
				mSelectHeadTv.setText("设置头像");
			}
			if (!TextUtils.isEmpty(login.getNickName())) {
				mNickNameEdit.setText(login.getNickName());
			}
			if (!TextUtils.isEmpty(login.getSex())) {
				if("1".equals(login.getSex())) {
					mSexBoyRadio.setChecked(true);
				} else if ("2".equals(login.getSex())) {
					mSexGirlRadio.setChecked(true);
				}
			}
			if (!TextUtils.isEmpty(login.getBirthday())) {
				mBirthdayEdit.setText(login.getBirthday());
			}
		}
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.head_layout:
			startGallery();
			break;
		case R.id.finish_btn:
			modifyUserInfo();
			break;
		default:
			break;
		}
	}
	
	private void modifyUserInfo() {
		mNickName = mNickNameEdit.getText().toString().trim();
		mBirthday = mBirthdayEdit.getText().toString().trim();
		
		if(TextUtils.isEmpty(mNickName)) {
			Toast.makeText(this, "昵称不能为空", Toast.LENGTH_SHORT).show();
			return;
		}
		if (AppMarketApplication.isLogin()) {
			showWaitDialog();
			mLogin = new Login();
			mLogin.setUserId(AppMarketApplication.getLogin().getUserId());
			mLogin.setNickName(mNickName);
			mLogin.setSex(mSex);
			mLogin.setBirthday(mBirthday);
			ModifyUserInfoNetEngine engine = new ModifyUserInfoNetEngine(mLogin);
			mNetTask2 = new NetTask(this, engine, 1);
			mNetTask2.setListener(this);
			new Thread(mNetTask2).start();
		} else {
			Toast.makeText(this, "修改信息失败，请先登录", Toast.LENGTH_SHORT).show();
		}
		
	}
	
	private void uploadUerIcon(String iconPath){
		UserIconNetEngine engine = new UserIconNetEngine(iconPath);
		mNetTask = new NetTask(this, engine, 0);
		mNetTask.setListener(this);
		new Thread(mNetTask).start();
	}
	
	private void startGallery() {
		Intent intent = new Intent(this, GalleryActivity.class);
		startActivityForResult(intent, REQUEST_GALLERY);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		if (!mIsShowMenu) {
			return super.onCreateOptionsMenu(menu); 
		}
		getMenuInflater().inflate(R.menu.register_menu, menu);
		final MenuItem item = menu.findItem(R.id.action_next);
		item.setTitle(R.string.ignore);
		LinearLayout itemLayout = (LinearLayout) item.getActionView();
		TextView title = itemLayout.findViewById(R.id.menu_title);
		title.setText(R.string.ignore);
		
		itemLayout.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
            	 ModifyUserInfoActivity.this.onOptionsItemSelected(item);
             }
         });
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			break;
		case R.id.action_next:
			finish();
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onDateSet(DatePicker view, int year, int monthOfYear,
			int dayOfMonth) {
		String birthday = year + "-" + (monthOfYear + 1)  + "-" + dayOfMonth;
		mBirthdayEdit.setText(birthday);
	}
	
	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		switch (checkedId) {
		case R.id.boy_radio_btn:
			mSex = "1";
			break;
		case R.id.gril_radio_btn:
			mSex = "2";
			break;
		default:
			break;
		}
	}
	
	@Override
	public void onTaskRunSuccessful(int tag, BaseNetEngine engine) {
		dismissWaitDialog();
		if (tag == 0) {
			UserIconResult resultData = (UserIconResult) engine.getResultData();
			if (!resultData.isOK()) {
				String message = resultData.getMessage();
				if (!TextUtils.isEmpty(message)) {
					Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(this, R.string.modify_user_icon_error, Toast.LENGTH_SHORT).show();
				}
			} else {
				Login loginResult = resultData.getLogin();
				// 保存头像url
				if (AppMarketApplication.isLogin()) {
					Login login = AppMarketApplication.getLogin();
					login.setIconUrl(loginResult.getIconUrl());
					LoginUtil.saveLogin(this, login);
				}
				Toast.makeText(this, R.string.modify_user_icon_success, Toast.LENGTH_SHORT).show();
			}
		}else if (tag == 1) {
			ModifyUserInfoResult resultData = (ModifyUserInfoResult) engine.getResultData();
			if (!resultData.isOK()) {
				String message = resultData.getMessage();
				if (!TextUtils.isEmpty(message)) {
					Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(this, R.string.modify_user_info_error, Toast.LENGTH_SHORT).show();
				}
			} else {
				// 保存昵称、性别、生日信息
				if (AppMarketApplication.isLogin()) {
					Login login = AppMarketApplication.getLogin();
					login.setNickName(mLogin.getNickName());
					login.setSex(mLogin.getSex());
					login.setBirthday(mLogin.getBirthday());
					LoginUtil.saveLogin(this, login);
				}
				Toast.makeText(this, R.string.modify_user_info_success, Toast.LENGTH_SHORT).show();
				finish();
			}
		}
	}

	@Override
	public void onTaskRunError(int tag) {
		dismissWaitDialog();
		Toast.makeText(this, R.string.network_error, Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onTaskRunCanceled(int tag) {
		dismissWaitDialog();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUEST_GALLERY && resultCode == RESULT_OK) {
			if (data != null) {
				String headIconPath = data.getStringExtra("head_icon_path");
				if (!TextUtils.isEmpty(headIconPath)) {
					mSelectHeadTv.setText("修改头像");
					mHeadImage.setImageBitmap(BitmapFactory.decodeFile(headIconPath));
					uploadUerIcon(headIconPath);
				}
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}
	
	@Override
	protected void onDestroy() {
		if (mNetTask != null) {
			mNetTask.cancel();
			mNetTask.setListener(null);
			mNetTask = null;
		}
		if (mNetTask2 != null) {
			mNetTask2.cancel();
			mNetTask2.setListener(null);
			mNetTask2 = null;
		}
		dismissDatePickerDialog();
		dismissWaitDialog();
		super.onDestroy();
	}

	private void showDatePickerDialog() {
		if (mDatePickerDialog == null) {
			int year = 1990;
			int month = 5;
			int day = 1;
			mDatePickerDialog = new DatePickerDialog(this, this, year, month, day);
		}
		if (mDatePickerDialog.isShowing()) {
			return;
		}
		String birthday = mBirthdayEdit.getText().toString().trim();
		if (!TextUtils.isEmpty(birthday)) {
			String[] s = birthday.split("-");
			if (s.length == 3) {
				int year = Integer.parseInt(s[0]);
				int month = Integer.parseInt(s[1]) - 1;
				int day = Integer.parseInt(s[2]);
				mDatePickerDialog.updateDate(year, month, day);
			}
		}
		mDatePickerDialog.show();
	}
	
	private void dismissDatePickerDialog() {
		if (mDatePickerDialog != null) {
			mDatePickerDialog.dismiss();
		}
	}

	private void showWaitDialog(){
		if (mWaitDialog == null) {
			mWaitDialog = new WaitDialog(this);
			mWaitDialog.setCanceledOnTouchOutside(false);
			mWaitDialog.setCancelable(false);
		}
		if (mWaitDialog.isShowing()) {
			return;
		}
		mWaitDialog.showTitle("请稍候...").show();
	}
	
	private void dismissWaitDialog(){
		if (mWaitDialog != null) {
			mWaitDialog.dismiss();
		}
	}
}
